#include "packdiyform.h"
#include "ui_packdiyform.h"
#include"data.h"
#include<QTimer>
#include<iostream>
using namespace std;
PackDiyForm::PackDiyForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::PackDiyForm)
{
    ui->setupUi(this);

    connect(ui->pushButton_add,&QPushButton::clicked,this,[=](){on_pushButton_add_clicked();});
    connect(ui->pushButton_startcom,&QPushButton::clicked,this,[=](){
        int axis[4] = { 0,1,2,3 };
        float POS[12] = { 0,0,0,100,100,100,100,0,0,0 };
        int otlist[5] = { 0,1,1,1,1 };
        PMC_SetMerge(Data::handle, 0, 1);//设置开启连续插补（开启主轴的即可，如轴 0，轴 1插补，轴 0 为主轴，主轴号取决于连续插补运动指令轴列表的第一个轴号）
        for(int i=0;i<modelist.size();++i){
            if(modelist[i]==0){
                PackDiyForm::getPos(1, 4,axis);
            }
            else{
                gopos(1, 5, 2, axis, POS, 5, otlist, 5000);
            }
        }
    });
    connect(ui->pushButton_startexe,&QPushButton::clicked,this,[=](){
        int axis[2] = { 0,1 };
        float POS[12] = { 0,0,0,100,100,100,100,0,0,0 };
        int otlist[5] = { 0,1,1,1,1 };
        PMC_SetMerge(Data::handle, 0, 1);//设置开启连续插补（开启主轴的即可，如轴 0，轴 1插补，轴 0 为主轴，主轴号取决于连续插补运动指令轴列表的第一个轴号）
        for(int i=0;i<modelist.size();++i){
            if(modelist[i]==0){
                PackDiyForm::getPos(2, 4,axis);
            }
            else{
                gopos(2, 5, 2, axis, POS, 5, otlist, 5000);
            }
        }
    });


    QTimer *timer1=new QTimer(this);
    connect(timer1,&QTimer::timeout,this,&PackDiyForm::updateWin);
    timer1->start(100);


}

PackDiyForm::~PackDiyForm()
{
    delete ui;




}

//command运行
void PackDiyForm::on_pushButton_startcom_clicked(){

}

//Execute运行
void PackDiyForm::on_pushButton_startexe_clicked(){

}




//添加指令
void PackDiyForm::on_pushButton_add_clicked(){
    if(ui->comboBox_select->currentText()=="获取坐标"){
        modelist.append(0);
        ui->textEdit_run->insertPlainText(">>获取坐标");
    }
    else if(ui->comboBox_select->currentText()=="运动集合"){
        modelist.append(1);
        ui->textEdit_run->insertPlainText(">>运动集合");
    }
}

//读取AXIS 0，AXIS 1，AXIS2 的命令位置
void PackDiyForm::getPos(int mode, int iaxisNum,int iaxislist[]){
    //QString log="";
    char cmdbuff[2048];
    char tempbuff[2048];
    char cmdbuffAck[20480];

    //生成命令
    snprintf(cmdbuff,sizeof(cmdbuff),"?");  //生成对应命令的字符串
    //拼接DPOS
    for(int i=0;i<iaxisNum;++i){
        snprintf(tempbuff,sizeof(tempbuff),"DPOS(%d),",i);   //生成对应命令的字符串
        strcat_s(cmdbuff,tempbuff); //字符串拼接
        if(strlen(cmdbuff)>1000){
            //log=timeNow.time()+":"+"getPos()参数错误，字符串拼接过长\n";
            ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+ "getPos()参数错误，字符串拼接过长\n");
        }
    }
    if(mode==1){
        PMC_Command(Data::handle,cmdbuff,cmdbuffAck,2048);

    }
    else{
        PMC_Execute(Data::handle,cmdbuff,cmdbuffAck,2048);
    }
    if(0==strlen(cmdbuffAck)){
        //log=log+"返回字符串为空\n";
        ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+ "返回字符串为空\n");

    }
    else{
        QVector<float> ftempbuff(iaxisNum);
        QStringList list=QString(cmdbuffAck).trimmed().split("\t");
        if(list.count()!=iaxisNum)
            return;
        for(int i=0;i<iaxisNum;++i){
            float floatValue=list[i].toFloat();
            //QString str=QString::number( cmdbuffAck[i]);  //从cmdbuffAck中提取单个字符
            //float floatValue=str.toFloat();
            ftempbuff[i]=floatValue;    //将cmdbuffAck中的每个值转换为浮点数并存储在ftempbuff中
        }
        //DPos输出
        for(int i=0;i<iaxisNum;++i){
            QString mes=QString::number( ftempbuff[i]);
            //log=log+mes.sprintf("轴&1点位为&2\n",i,ftempbuff[i]);
            char cstr[2048];
            sprintf(cstr,"轴%d点位为%f\n",i,ftempbuff[i]);
            ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+QString(cstr)+"\n");

         //   sprintf("轴%i点位为%d\n",i,ftempbuff[i])
        }
    }
    //ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+ log);
}


//假设控制一个 XY 两轴平台，从坐标点（0,0）—>（100,0）（输出口 0 输出 50ms）
//—>（100,100）（输出口 0 输出 50ms）—>（0,100）（输出口 0 输出 50ms）—>（0,0）
//（输出口 0 输出 50ms）的轨迹，则可以通过自己封装，用一条函数，快速发送下去。
void PackDiyForm::gopos(int mode, int iMoveLen,int iaxisNum,int* iaxislist,float* fPoslist,int iout,int* outlist,int outtime){
    char cmdbuff[2048];
    char tempbuff[2048];
    char cmdbuffAck[20480];
    //读取剩余直线缓冲
    int iBuffLen=0;
    PMC_GetRemain_LineBuffer(Data::handle,0,&iBuffLen);
    if(iBuffLen<=iMoveLen*2){
        ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+"运动缓冲不足");
    }
    //生成命令
    snprintf(cmdbuff,sizeof(cmdbuff),"BASE(");
    //拼接运动轴列表
    for(int i=0;i<iaxisNum;++i){
        if(i<iaxisNum-1){
            snprintf(tempbuff,sizeof(tempbuff),"%d,",i); //生成对应命令的字符串

        }
        else{
            snprintf(tempbuff,sizeof(tempbuff),"%d)\n",i);
        }
        strcat_s(cmdbuff,tempbuff); //字符串拼接
        if(strlen(cmdbuff)>1000){
            ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+"参数错误，字符串拼接过长");
        }
    }
    //拼接运动
    for(int i=0;i<iMoveLen;++i){
        if(outlist[i]==0){   //该运动没有out输出
            strcat_s(cmdbuff,"MoveAbs(");
            snprintf(tempbuff,sizeof(tempbuff),"%f,%f)\n",fPoslist[i * iaxisNum],fPoslist[i * iaxisNum+1]);  //生成对应命令字符串
            strcat_s(cmdbuff,tempbuff); //拼接
        }
        else if(outlist[i]==1){
            strcat_s(cmdbuff,"MoveAbs(");
            snprintf(tempbuff,sizeof(tempbuff),"%f,%f)\n",fPoslist[i * iaxisNum],fPoslist[i * iaxisNum + 1]);
            strcat_s(cmdbuff,tempbuff);
            strcat_s(cmdbuff,"Move_op2(");
            snprintf(tempbuff,sizeof(tempbuff),"%d,%d,%d)\n",iout,1,outtime);
            strcat_s(cmdbuff,tempbuff);
        }
        else{
            ui->textEdit_log->insertPlainText(timeNow.time().toString()+":"+"参数错误");
        }

    }
    if(mode==1){
        PMC_Command(Data::handle,cmdbuff,cmdbuffAck,2048);

    }
    else{
        PMC_Execute(Data::handle,cmdbuff,cmdbuffAck,2048);
    }



}


//窗口更新
void PackDiyForm::updateWin(){

    if(Data::handle!=nullptr){
        float dpos=0;
        for(int i=0;i<4;++i){
            PMC_GetDpos(Data::handle,axislist[i],&dpos);
            QString pos = QString::number( dpos,'f',3);
            if(i==0) ui->label_xpos->setText(pos);
            else if(i==1) ui->label_ypos->setText(pos);
            else if(i==2) ui->label_zpos->setText(pos);
            else if(i==3) ui->label_upos->setText(pos);
        }
        if(runflage){
            int value[4]={0,0,0,0};
            for(int i=0;i<4;++i){
                PMC_GetIfIdle(Data::handle,i,&value[i]);
            }
            //cout<<value[0]<<"_"<<value[1]<<"_"<<value[2]<<"_"<<value[3]<<endl;
            if(value[0]==-1&&value[1]==-1&&value[2]==-1&&value[3]==-1){
                runflage=false;
                ui->pushButton_startcom->setEnabled(true);
                ui->pushButton_startexe->setEnabled(true);
                ui->label_flag->setText("停止");
                ui->label_flag->setStyleSheet("background-color: rgb(255,0,0)");
            }
        }
    }
}

void PackDiyForm::showEvent(QShowEvent *event){
    QList<QString> optionsmode={"获取坐标","运动集合"};
    ui-> comboBox_select->addItems(optionsmode);
    ui->textEdit_log->setReadOnly(true);
    ui->textEdit_run->setReadOnly(true);
}

